import {useRef,useEffect} from "react"

/**
 * 防抖
 * @param fn
 * @param delay
 */
export function debounce(fn, delay) {
  delay = delay || 600
  let timer
  return function () {
    let ctx = this
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fn.apply(ctx, args)
    }, delay)
  }
}

/**
 * 节流
 * @param fn
 * @param interval
 */
export function throttle(fn, interval) {
  let last
  let timer
  interval = interval || 600
  return function () {
    let ctx = this
    let args = arguments
    let now: any = new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now
        fn.apply(ctx, args)
      }, interval)
    } else {
      last = now
      fn.apply(ctx, args)
    }
  }
}


type Fn = (...args: any) => any;

export function useThrottleFn<T extends Fn>(fn: T, time: number): T {
  const fnRef = useRef<Fn>(fn);
  fnRef.current = fn;

  const wait = time ?? 1000;

  const throttled = useCreation(
    () =>
      throttle(
        (...args: any) => {
          fnRef.current(...args);
        },
        wait,
      ),
    [],
  );

  return (throttled as any) as T;
}

export default function useCreation<T>(factory: () => T, deps: any[]) {
  const {current} = useRef({
    deps,
    obj: undefined as undefined | T,
    initialized: false,
  });
  if (current.initialized === false || !depsAreSame(current.deps, deps)) {
    current.deps = deps;
    current.obj = factory();
    current.initialized = true;
  }
  return current.obj as T;
}

function depsAreSame(oldDeps: any[], deps: any[]): boolean {
  if (oldDeps === deps) return true;
  for (const i in oldDeps) {
    if (oldDeps[i] !== deps[i]) return false;
  }
  return true;
}

// // taro api 转promise 辅助函数
// interface TaroApiParamsCommon {
//   fail?: (res: General.CallbackResult) => void,
//   success?: (res: General.CallbackResult) => void,
//   complete?: (res: General.CallbackResult) => void
// }
//
// interface TaroApi {
//   (params: TaroApiParamsCommon): void
// }
//
// export function taroApiHelp<P extends TaroApiParamsCommon, R extends General.CallbackResult = any>(api: TaroApi, params: Exclude<P, TaroApiParamsCommon>): Promise<R> {
//   return new Promise<R>(((resolve, reject) => {
//     api({
//       ...params,
//       fail: (err) => {
//         reject(new Error(err.errMsg))
//       },
//       success: (result) => {
//         resolve(result as R);
//       }
//     })
//   }));
// }
// 转换时间
export function transTime(timestamp:number):string {
  // return timestamp.toString()
  let result = "";
  if (timestamp >= 86400) {
    let $days = Math.floor(timestamp / 86400);
    timestamp = timestamp % 86400;
    result = $days + '天 ';
    if (timestamp > 0) {
      result += ' ';
    }
  }
  if (timestamp >= 3600) {
    let $hours:string | number = Math.floor(timestamp / 3600);
    timestamp = timestamp % 3600;
    if ($hours < 10) {
      $hours = '0' + $hours;
    }
    result += $hours + ':';

  }
  if (timestamp >= 60) {
    let $minutes:number|string = Math.floor(timestamp / 60);
    timestamp = timestamp % 60;
    if ($minutes < 10) {
      $minutes = '0' + $minutes;
    }
    result += $minutes + ':';
  }
  let $secend:string | number = Math.floor(timestamp);
  if ($secend < 10) {
    $secend = '0' + $secend;
  }
  result += $secend;
  return result;
}

type useIntervalCallback = (id)=>void
export  function useInterval(callback:useIntervalCallback, delay:number) {
  const savedCallback = useRef<useIntervalCallback|undefined>();
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);
  useEffect(() => {
    if (delay !== null) {
      let id = setInterval(()=> savedCallback!.current?.(id), delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}



